package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Attendance;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.AttendanceMapper;
import cn.wolfcode.crm.query.impl.AttendanceQuery;
import cn.wolfcode.crm.service.IAttendanceService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class AttendanceServiceImpl implements IAttendanceService {
    @Autowired
    private AttendanceMapper mapper;


    public PageResult query(AttendanceQuery qo) {
        int rows = mapper.queryForCount(qo);
        if (rows == 0) {
            new PageResult(rows, Collections.EMPTY_LIST);
        }
        List<Attendance> data = mapper.queryForList(qo);
        return new PageResult(rows, data);
    }

    public void sign() {
        Attendance attendance = new Attendance();
        Date date = new Date();
        Employee currentUser = UserContext.getCurrentUser();
        attendance.setUser(currentUser);
        attendance.setSignDate(date);
        attendance.setSignTime(date);
        mapper.insert(attendance);

        System.out.println("-----------");
    }

    public void signOut() {
        Session session = UserContext.getSession();

        Employee currentUser = (Employee) session.getAttribute("currentUser");

        Date date = (Date) session.getAttribute("date");

        Attendance attendance = verify();
        attendance.setSignOutTime(new Date());

        mapper.updateByUserAndSignTime(attendance);

    }

    public Attendance verify() {
        Employee user = UserContext.getCurrentUser();
        //时间格式
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        //时间字符串
        String format = format1.format(new Date());
        Date date1=null;
        try {
            date1 = format1.parse(format);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Attendance id2Date = mapper.selectByUserId2Date(user, date1);
        System.out.println(id2Date);
        return id2Date;
    }

}
